<!-- 新增用户 -->
<template>
  <Modal
    class="add_form"
    v-model="modal"
    title="添加用户到角色"
    :mask-closable="false"
    draggable
    sticky
    scrollable
    @on-cance="cancel"
    @on-visible-change="cancel"
    width="400px"
  >
    <Form
      ref="formEl"
      :model="formData"
      :rules="rules"
      :label-width="80"
    >
      <div class="flex_form_item">
        <FormItem label="用户" prop="ids">
          <Select
            v-model="formData.ids"
            transfer
            multiple
            filterable
            placeholder="请选择用户"
          >
            <Option
              v-for="item in userGather"
              :value="item.id"
              :key="item.id"
            >{{ item.username }} {{ item.uname ? `(${item.uname})` : '' }}</Option>
          </Select>
        </FormItem>
      </div>
    </Form>

    <template #footer>
      <Button @click="cancel">取消</Button>
      <Button
        type="primary"
        @click="submit"
      >确定</Button>
    </template>
  </Modal>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { Message } from 'view-ui-plus'
import { userList } from '@/api/modules/department'
import { roleAddrole } from '@/api/modules/role'

const emit = defineEmits(['cancel', 'submit'])

// 是否打开弹窗
const modal = ref(true)

// 加载
const loading = ref(true)

// 表单元素ref
const formEl = ref(null)

const roleId = ref(null)
// 表单字段
const formData = ref({
  ids: []
})

// 表单校验条件
const rules = ref({
  ids: [{ required: true, type: 'array', message: '请选择用户', trigger: 'blur' }]
})

const userGather = ref([])
const getUserList = reset => {
  userList({
    query: {
      p: 1,
      // ps: pageSize
    }
  }).then(({ data }) => {
    userGather.value = data.topicList
  })
}

/**
 * 提交表单
 */
const submit = async () => {
  let valid = await formEl.value.validate()
  if (!valid) return

  loading.value = true

  try {
    await roleAddrole({
      data: {
        ...formData.value,
        id: roleId.value
      }
    })
    Message.success('操作成功')

    emit('submit')
    
  } catch (error) {
    console.log(error)
  }

  loading.value = false
}

/**
 * 取消表单
 */
const cancel = () => {
  emit('cancel')
}

const initDialog = (id) => {
  roleId.value = id
}

defineExpose({
  initDialog
})

onMounted(() => {
  getUserList()
})
</script>

<style scoped lang="scss">
::deep(.ivu-form-item-label) {
  text-align: right;
}
</style>